package com.cheil.publish.web;

import com.cheil.publish.service.data.ChatsDto;
import com.cheil.publish.service.publish.AutoPublishService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 @author ssk
 @date 2025/9/10
 **/
@Tag(name = "自动发布")
@Controller
@RequestMapping("/auto")
@Slf4j
@AllArgsConstructor
public class AutoPublishController  {

    private final AutoPublishService autoPublishService;


    @GetMapping("/index")
    public String index() {
        return "xiaohongshu-publish";
    }

    @GetMapping("/login")
    public void login(HttpServletResponse response) {

        try {
            String loginQrcode = autoPublishService.login();
            log.info("loginQrcode:{}", loginQrcode);

            // 去掉可能存在的 data:image/png;base64, 前缀
            String base64 = loginQrcode;
            if (loginQrcode.contains(",")) {
                base64 = loginQrcode.substring(loginQrcode.indexOf(",") + 1);
            }
            byte[] imgBytes = Base64.getDecoder().decode(base64);

            response.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
            response.setContentLength(imgBytes.length);
            response.getOutputStream().write(imgBytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("login error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/publish")
    @ResponseBody
    public void publish(@RequestParam String title,
                        @RequestParam String content,
                        @RequestParam(required = false) String location,
                        @RequestParam("images") List<MultipartFile> images,
                        @RequestParam(required = false) List<String> tags) {

        log.info("收到发布请求：title={}, contentLen={}, location={}, images={}, tags={}",
                 title, content.length(), location, images.size(), tags);

        // 这里可以调用 service 做真正的发布逻辑
        ChatsDto dto = new ChatsDto(title, content, null, null, tags);
        autoPublishService.publish(dto, images);
    }
}
